package cc.messcat.web.system;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.fupin.PoorVillage;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.helpUnits.HelpTeamPerson;
import cc.messcat.entity.helpUnits.HelpUnits;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.area.AreaService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.PoorVillageService;
import cc.messcat.service.helppeson.HelppesonService;
import cc.messcat.service.helpunits.HelpunitsService;
import cc.messcat.util.Collections;

/**
 * 帮扶负责人
 *
 * @author John
 */
@Controller
@RequestMapping("/helppeson")
public class HelppersonController {

    @Autowired
    public HelppesonService helppesonService;

    @Autowired
    public PoorVillageService poorVillageService;

    @Autowired
    public HelpunitsService helpunitsService;

    @Autowired
    private PoorFamilyService poorFamilyService;
    
    @Autowired
    @Qualifier("areaServiceImpl")
    public AreaService areaService;
    
    public HelpTeamPerson helpTeamPerson;


	// 扶贫负责人管理查询
//	@OperationLog(desc = "扶贫负责人管理查询", module = "扶贫主体管理")
	@RequestMapping(value = "/findAllhelppeson", method = RequestMethod.POST)
	@ResponseBody
	public Object findAllhelppeson(Integer pageNo, Integer pageSize, String unitName, String name, String idNumber, String tel,
		HttpSession session) throws Exception {
		pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
		pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;

		McUser user = (McUser) session.getAttribute("user");
		Pager pager = helppesonService.listHelpPerson(pageNo, pageSize, user, unitName, name, idNumber, tel);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
	}

    //查询
    @RequestMapping(value = "/findAllhelppesonNew", method = RequestMethod.POST)
    @ResponseBody
    public Object findAllhelppesonNew(Integer pageNo, Integer pageSize, String Affiliation, String Unit_name, String telephone_number) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Pager pager = this.helppesonService.getPageNew(pageNo, pageSize, Affiliation, Unit_name, telephone_number);
        //List<HelpPerson> resultList = helppesonService.retrieveAllObjects();
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }


    //根据id查询帮扶负责人
    @OperationLog(desc="根据id查询帮扶负责人",module="扶贫主体管理")
    @RequestMapping(value = "/findhelppeson", method = RequestMethod.POST)
    @ResponseBody
    public Object findhelppeson(Long id) throws Exception {
        HelpPerson resultList = helppesonService.helpPersons(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, resultList);
    }
    
    
    //根据id查询多个帮扶负责人
    @RequestMapping(value = "/findhelppesonMultiple", method = RequestMethod.POST)
    @ResponseBody
    public Object findhelppesonMultiple(HttpServletRequest request) throws Exception {
    	
    	String sid = request.getParameter("sid");
    	if(org.apache.commons.lang.StringUtils.isBlank(sid)) {
    		 return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS);
    	}
        String[] spli = sid.split(",");
        HelpPerson resultList = null;
        ArrayList arrayList= new ArrayList<>();
        for (int i = 0; i < spli.length; i++) {
        	 resultList = helppesonService.helpPersons(Long.valueOf(spli[i]));
        	 arrayList.add(resultList);
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS,arrayList);
    }


    //根据id查询帮扶单位
    @OperationLog(desc="根据id查询帮扶单位",module="扶贫主体管理")
    @RequestMapping(value = "/findhelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object findhelpunits(Long id) throws Exception {
        List<HelpUnits> resultList = helppesonService.getHelpUnitByHelpPersonID(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, resultList);
    }


    //扶贫负责人添加
    @OperationLog(desc="扶贫负责人添加",module="扶贫主体管理")
    @RequestMapping(value = "/addhelppeson", method = RequestMethod.POST)
    @ResponseBody
    public Object addhelppeson(HelpPerson helpPerson, Long HELP_UNIT) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
//		helpPerson.setAnnual(datetime);
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getSession().getAttribute("user");
        if (obj != null) {
            McUser loginUser = (McUser) obj;
            helpPerson.setModifier(loginUser.getUsername());
        }
        HelpUnits helpUnits= helpunitsService.get(HELP_UNIT);
        helpPerson.setHelpUnitName(helpUnits.getUnit_address());
        helpPerson.setAffiliation(helpUnits.getAffiliation());
        helppesonService.addHelppeson(helpPerson, HELP_UNIT);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS, helpPerson);
    }

    //帮扶负责人修改
    @OperationLog(desc="帮扶负责人修改",module="扶贫主体管理")
    @RequestMapping(value = "/updatehelppeson", method = RequestMethod.POST)
    @ResponseBody
    public Object updatehelppeson(HelpPerson helpPerson, Long HELP_UNIT) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getSession().getAttribute("user");
        if (obj != null) {
            McUser loginUser = (McUser) obj;
            helpPerson.setModifier(loginUser.getUsername());
        }
//        helpPerson.setAnnual(datetime);
        helpPerson.setStatus("1");
        HelpUnits helpUnits= helpunitsService.get(HELP_UNIT);
        helpPerson.setHelpUnitName(helpUnits.getUnit_address());
        helpPerson.setUnit_name(helpUnits.getUnit_name());
        helpPerson.setAffiliation(helpUnits.getAffiliation());
        helppesonService.modifyHelppesons(helpPerson, HELP_UNIT);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, helpPerson);
    }


    //修改
    @OperationLog(desc="帮扶负责人根据id修改",module="扶贫主体管理")
    @RequestMapping(value = "/updatehelp", method = RequestMethod.POST)
    @ResponseBody
    public Object updatehelp(Long id) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
        HelpPerson helpPerson = helppesonService.retrieveObject(id);
//        helpPerson.setAnnual(datetime);
        helppesonService.modifyHelppeson(helpPerson);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, helpPerson);
    }


    //修改帮扶负责人外键id
    @OperationLog(desc="修改帮扶负责人外键id",module="扶贫主体管理")
    @RequestMapping(value = "/updatehelpperson", method = RequestMethod.POST)
    @ResponseBody
    public Object updatehelpperson(Long id, Long HELP_UNIT,String unit_name) throws Exception {
    	if(HELP_UNIT == null) {
    		return new ResponseBean(CommonConstant.EXCEPTION_CODE_500,"没有选择帮扶单位");
    	}
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
        HelpPerson helpPerson = helppesonService.retrieveObject(id);
//        helpPerson.setAnnual(datetime);
        helppesonService.modifyHelppesonunit(helpPerson, HELP_UNIT, unit_name);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, helpPerson);
    }


    //扶贫负责人删除
    @OperationLog(desc="扶贫负责人删除",module="扶贫主体管理")
    @RequestMapping(value = "/delecthelppeson", method = RequestMethod.POST)
    @ResponseBody
    public Object delecthelppeson(Long id) throws Exception {
        HelpPerson hp = helppesonService.retrieveObject(HelpPerson.class, id);
        hp.setStatus("0");
        
        //负责人与贫困户中间表维护
        if(!Collections.isEmpty(helppesonService.checkHelpPersonAndPoorFamily(id))) {
        	return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "该帮扶责任人已关联贫困户，无法删除", "failed");
        }
        
        helppesonService.modifyObject(hp);
//        helppesonService.removeObject(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS, id);
    }


    //结对多对多贫困村
    @OperationLog(desc="帮扶单位结对贫困村",module="扶贫主体管理")
    @RequestMapping(value = "/addhelpoor", method = RequestMethod.POST)
    @ResponseBody
    public Object addhelpoor(Long helpPersonid, String sid,HttpServletRequest request) throws Exception {
        List<PoorVillage> poorVillages = poorVillageService.poorVillages(helpPersonid);
        List<String> spli = new ArrayList(Arrays.asList(sid.split(",")));
        HelpUnits helpUnits = helpunitsService.retrieveObject(helpPersonid);
        
        List<PoorVillage> poorVillages3 = helpUnits.getPoorVillages();
        Iterator<PoorVillage> it = poorVillages3.iterator();
        while (it.hasNext()) {
        	PoorVillage next = it.next();
        	if(spli.contains(next.getId().toString())) {
        		it.remove();
        	}
        	
		}
        for (int i = 0; i < spli.size(); i++) {
            PoorVillage poorVillages2 = poorVillageService.get(Long.valueOf(spli.get(i)));
            poorVillages.add(poorVillages2);
        }
        poorVillages.addAll(poorVillages3);
        helpUnits.setPoorVillages(poorVillages);
        helpunitsService.modifyHelpu(helpUnits);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "结对成功");
    }
    
  /*  //结对一对多贫困村
    @OperationLog(desc="结对一对多贫困村查询",module="帐表查询")
    @RequestMapping(value = "/addhelpoor", method = RequestMethod.POST)
    @ResponseBody
    public Object addhelpoor(HttpServletRequest request, Long helpPersonid) throws Exception {

        List<PoorVillage> poorVillages = poorVillageService.poorVillages(helpPersonid);
        String sid = request.getParameter("sid");
        String[] spli = sid.split(",");
        for (int i = 0; i < spli.length; i++) {
            PoorVillage poorVillages2 = poorVillageService.get(Long.valueOf(spli[i]));
            poorVillages.add(poorVillages2);
        }
        HelpUnits helpUnits = helpunitsService.retrieveObject(helpPersonid);
        helpUnits.setPoorVillages(poorVillages);
        helpunitsService.modifyHelpu(helpUnits);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
    }*/
    
    
    //解除多对多贫困村
    @OperationLog(desc="帮扶单位解除结对贫困村",module="扶贫主体管理")
    @RequestMapping(value = "/removeAddhelpoors", method = RequestMethod.POST)
    @ResponseBody
    public Object removeAddhelpoors(Long id,String sid,HttpServletRequest request) throws Exception {
        helpunitsService.removeAddhelpoors(id,sid);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "解除成功");
    }


    //结对解除一对多贫困村
    @OperationLog(desc="结对解除一对多贫困村",module="扶贫主体管理")
    @RequestMapping(value = "/delectaddhelpoor", method = RequestMethod.POST)
    @ResponseBody
    public Object delectaddhelpoor(HttpServletRequest request, Long id) throws Exception {
			/*List<PoorVillage> poorVillages=poorVillageService.poorVillages(id);*/
        String sid = request.getParameter("sid");
        String[] spli = sid.split(",");
        String aa = spli[0];
            /*for (int i = 0; i < poorVillages.size(); i++) {

				poorVillages.get(i).setHelpPerunit(null);
				
				poorVillageService.modifyPoorVillage(poorVillages.get(i));
			}
			*/
        for (int i = 0; i < spli.length; i++) {
            PoorVillage poorVillage = poorVillageService.get(Long.valueOf(spli[i]));
            Long a = poorVillage.getHelpPerunit();
            List<HelpTeamPerson> helpTeamPerson=helppesonService.getPerson_id(a); 
            for (HelpTeamPerson helpTeamPerson2 : helpTeamPerson) {
            	helpTeamPerson2.setStatus("0");
                helppesonService.modifyHelppeson(helpTeamPerson2);
			}
            poorVillage.setHelpPerunit(null);
            poorVillageService.modifyPoorVillage(poorVillage);
        }
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
    }


    //查询
    @RequestMapping(value = "/getHelpPresonsNotInTeam", method = RequestMethod.POST)
    @ResponseBody
    public Object getHelpPresonNotInTeam(Integer pageNo, Integer pageSize, Long unitId, Long villageId) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Pager pager = this.helppesonService.getHelpPresonsNotInTeam(pageNo, pageSize, unitId, villageId);
        //List<HelpPerson> resultList = helppesonService.retrieveAllObjects();
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    //url:helppeson/getHelpPersonByAreaId
    //查询,根据村ID,找到对应的单位,以及单位下的负责人
//    @OperationLog(desc="查询,根据村ID,找到对应的单位,以及单位下的负责人",module="扶贫主体管理")
    @RequestMapping(value = "/getHelpPersonByAreaId")
    @ResponseBody
    public Object getHelpPersonByAreaId(Long areaId, Integer pageNo, Integer pageSize,String unitName, String name,String idNumber) {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        //20171214   帮扶负责人结对信息变动
       /* PoorVillage poorVillage = poorVillageService.getVillageByAreaId(areaId);   
        if (poorVillage == null) return new ResponseBean(CommonConstant.FAIL_CODE_400, "该地区还未绑定村子");
        if (poorVillage.getHelpPerunit() == null) return new ResponseBean(CommonConstant.FAIL_CODE_400, "该村子还未绑定帮扶单位");
        List<HelpPerson> helpPeople = helppesonService.helpPerson(poorVillage.getHelpPerunit());*/
        
        List<HelpPerson> helpPeople = new ArrayList<>();
        PoorVillage poorVillage = poorVillageService.getVillageByAreaId(areaId);
        if(poorVillage == null ||"".equals(poorVillage)){
        	 return new ResponseBean(CommonConstant.SUCCESS_CODE_200, "请先帮扶责任人！");
        }
        List<HelpUnits> helpUnits = (List<HelpUnits>) helpunitsService.getHelpUnits(poorVillage.getId());
       
        for (HelpUnits e : helpUnits) {
        	if(StringUtils.isNotBlank(unitName)) {
        		if(StringUtils.isBlank(e.getUnit_name()) || !e.getUnit_name().contains(unitName)) continue;
        	}
        	
        	List<HelpPerson> helpPerson = e.getHelpPerson();
        	Iterator<HelpPerson> iterator = helpPerson.iterator();
        	while (iterator.hasNext()) {
        		HelpPerson hp = iterator.next();
        		if("0".equals(hp.getStatus())) {
        			continue;
        		}
        		if(StringUtils.isNotBlank(name)) {
            		if(StringUtils.isBlank(hp.getName()) || !hp.getName().contains(name)) continue;
            	}
            	if(StringUtils.isNotBlank(idNumber)) {
            		if(StringUtils.isBlank(hp.getID_number()) || !hp.getID_number().contains(idNumber)) continue;
            	}
            	helpPeople.add(hp);
			}
		}
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS,helpPeople);
    }
    
    
    //扶贫负责人结对判断
//    @OperationLog(desc="扶贫负责人结对判断",module="扶贫主体管理")
    @RequestMapping(value = "/helppesonJudge", method = RequestMethod.POST)
    @ResponseBody
    public Object helppesonJudge(Long id) throws Exception {
        boolean helpPerson = helppesonService.helppesonJudge(id);

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS, helpPerson);
    }
    
    /**
     * 帮扶负责人结对贫困户
     * @return
     */
    @RequestMapping(value = "/associateHP", method = RequestMethod.POST)
    @ResponseBody
    @OperationLog(desc="帮扶负责人结对贫困户",module="扶贫对象管理")
    public Object associateHelpPersonAndPoorFamily(@RequestParam(name="poorFamilyId",required=true) Long poorFamilyId ,
    	@RequestParam(name="helpPersonIds",required=false,defaultValue="") String helpPersonIds) {
    	List<HelpPerson> list = new ArrayList<>();
    	if(helpPersonIds.matches("([0-9 ,])+")) {
    		list = helppesonService.listHelpPerson(helpPersonIds);
    		PoorFamily poorFamily = poorFamilyService.get(poorFamilyId);
    		poorFamily.setHelpPersons(list);
    		poorFamilyService.modifyObject(poorFamily);
    	}
    	return new ResponseBean(CommonConstant.SUCCESS_CODE_200,"关联成功",list);
    }
    
    /**
     * 查询指定帮扶责任人所帮扶的贫困户
     * @param helpPersonID
     * @return
     */
    @RequestMapping("/listPoorFamilyByHelpPerson")
    @ResponseBody
    public Object listPoorFamilyByHelpPerson(@RequestParam(name="helpPersonID",required=true)Long helpPersonID) {
    	List<Map<String,Object>> list = helppesonService.listPoorFamilyByHelpPerson(helpPersonID);
    	return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS, list);
    	
    }
}
